import './App.css';
import React from 'react';
import { Button, Grid, Toast, NavBar, Icon } from 'antd-mobile';
import * as request from './request';
import addPng from './static/add.svg'
import Toolbar from "./Toolbar";
import { connect } from 'react-redux';
import ico_avatar from './static/ico_avatar.svg';

const apiURL = "/api/services/app/Edu_Children/GetList?SkipCount=0&MaxResultCount=10&memberId=";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      childData: [],
    }
  }
  componentDidMount() {
    this.fetchData();
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  }
  fetchData = () => {
    Toast.loading('Loading...', 0);
    var mid = this.props.match.params.memberid;
    if (!mid)
      mid = localStorage.getItem('memberId');

    request.get(apiURL + mid)
      .then((data) => {
        Toast.hide();
        this.setState({ childData: data.result.items });
        var currentUser = this.props.currentUser;
        if (currentUser) {
          currentUser.childs = data.result.items
          this.props.dispatch({
            type: "setCurrUser",
            data: currentUser,
          })
        }
      })
      .catch((error) => {
        console.log('fetch data failed', error);
      });
  }
  goto = (item) => {
    if (item.childid === 0) {
      this.props.history.push('/BabyEdit/0');
    }
    else {
      const { childData } = this.state;
      var obj = childData.filter(i => i.id == item.childid)[0];
      localStorage.setItem('childid', item.childid);
      this.props.dispatch({
        type: "setCurrChild",
        data: obj,
      })
      this.props.history.push('/ChildDtl/');
    }
  }

  render() {
    const { childData } = this.state;
    const data = childData.map((item, i) => ({
      icon: item.avatar ? request.imgServer + item.avatar : ico_avatar,
      text: item.name,
      name: item.name,
      id: item.id,
      avatar: item.avatar,
      childid: item.id
    }));
    var obj = {
      icon: addPng,
      text: '添加宝宝',
      childid: 0
    }
    data.push(obj);
    return (
      <div>
        <NavBar
          icon={<Icon type="left" />}
          onLeftClick={() => this.props.history.push('/Home')}
          rightContent={[
            <Icon key="1" type="ellipsis" />,
          ]}
          style={{ position: "absolute", top: 0, zIndex: 99, width: '100%' }}>宝宝选择</NavBar>
        <div style={{ marginTop: 45 }}>
          <Grid data={data} columnNum={2} onClick={(item) => this.goto(item)} />
        </div>
        <Toolbar history={this.props.history} />
      </div>
    )
  };
}
export default connect(
  state => ({ currentUser: state.setCurrentUser, currentChild: state.setCurrentChild })
)(App)
